package com.lvy.hczn.front.system.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvy.hczn.front.common.core.domain.AjaxResult;
import com.lvy.hczn.front.common.core.redis.RedisCache;
import com.lvy.hczn.front.common.exception.UtilException;
import com.lvy.hczn.front.system.domain.business.Category;
import com.lvy.hczn.front.system.mapper.CategoryMapper;
import com.lvy.hczn.front.system.service.CategoryService;
import com.lvy.hczn.mq.rocket.ProducerUtil;
import com.lvy.hczn.front.common.constant.MqConstants;
import com.lvy.hczn.mq.rocket.ParamInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private ProducerUtil producerUtil;

    @Autowired
    private RedisCache redisCache;

    /**
     * 商品类别同步列表
     *
     * @param info
     * @return
     */
    @Override
    public AjaxResult syncCategoryBatch(HttpServletRequest request, ParamInfo info, boolean platform) throws Exception {
        if (info.getList() == null || info.getList().isEmpty()) {
            throw new UtilException("数据为空，请检查数据格式");
        }
        log.error("syncCategoryBatch:{}", JSON.toJSONString(info));
        List<Category> list = JSON.parseArray(JSON.toJSONString(info.getList()), Category.class);
        list.forEach(item -> {
            item.setId(item.getCategoryId());
            if (StrUtil.isEmpty(item.getCateCode())) {
                item.setCateCode(item.getId());
            }
            super.saveOrUpdate(item);
        });
        if (platform) {
            //若是平台同步，则发送到仓库
            try {
                info.setList(list);
                producerUtil.sendAsyncMsg(MqConstants.TOPIC_SYNC_CATEGORY, null, JSON.toJSONString(info).getBytes(StandardCharsets.UTF_8), IdUtil.fastUUID());
                /*String key = RedisConstants.WAREHOUSE_CODE_SPU + ":" + info.getWarehouseCode();
                redisCache.set(key, info);
                convertData(info);
                redisCache.del(key);*/
            } catch (Exception e) {
                log.error("syncCategoryBatch商品分类同步异常：{}", e);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 商品类别同步
     *
     * @param info
     * @return
     */
    @Override
    public AjaxResult syncCategory(HttpServletRequest request, ParamInfo<Category> info, boolean platform) throws Exception {

        if (info.getData() == null) {
            throw new UtilException("数据为空，请检查数据格式");
        }
        log.error("syncCategory:{}", JSONUtil.toJsonStr(info));
        /*if (StrUtil.isEmpty(info.getData().getCateCode())) {
            throw new UtilException("分类编码为空");
        }*/
        Category category = JSONUtil.toBean(JSONUtil.toJsonStr(info.getData()), Category.class);
        category.setId(category.getCategoryId());
        if (StrUtil.isEmpty(category.getCateCode())) {
            category.setCateCode(category.getId());
        }
        super.saveOrUpdate(category);
        if (platform) {
            ThreadUtil.execAsync(() -> {
                try {
                    ParamInfo<Category> categoryParamInfo = new ParamInfo<>();
                    categoryParamInfo.setData(category);
                    producerUtil.sendAsyncMsg(MqConstants.TOPIC_SYNC_CATEGORY, null, JSONUtil.toJsonStr(categoryParamInfo).getBytes(StandardCharsets.UTF_8), IdUtil.fastUUID());
                /*String key = RedisConstants.WAREHOUSE_CODE_SPU + info.getData().getCategoryId();
                redisCache.set(key, info);
                convertData(info);
                redisCache.del(key);*/
                } catch (Exception e) {
                    log.error("syncCategory商品分类同步异常：{}", e);
                }
            });
        }

        return AjaxResult.success();
    }

    public void convertData(ParamInfo<Category> info) throws Exception {
        ParamInfo<Category> categoryParamInfo = new ParamInfo<>();
        if (info.getList() != null && !info.getList().isEmpty()) {
            categoryParamInfo.setList(new ArrayList<>());
            for (int i = 0; i < info.getList().size(); i++) {
                Category category = JSONUtil.toBean(JSONUtil.toJsonStr(info.getList().get(i)), Category.class);
                categoryParamInfo.getList().add(category);
            }
        } else {
            if (info.getData() != null && StrUtil.isNotEmpty(info.getData().getCategoryId())) {
                Category category = JSONUtil.toBean(JSONUtil.toJsonStr(info.getData()), Category.class);
                categoryParamInfo.setData(category);
            } else {
                throw new UtilException("数据为空，请检查数据格式");
            }
        }
        categoryParamInfo.setWarehouseCode(info.getWarehouseCode());
        producerUtil.sendMsg(MqConstants.TOPIC_SYNC_CATEGORY, null, JSONUtil.toJsonStr(categoryParamInfo).getBytes(StandardCharsets.UTF_8), IdUtil.fastUUID());
    }
}
